import React from 'react';
import { connect } from 'react-redux';
import * as actions from './../../actions/a_bind';
import { getPersonalInfo } from './../../actions/a_personal_info';
import { Toast, Dialog } from 'react-weui';
import { parseQueryString } from './../../utils';
import classnames from 'classnames';

class BindView extends React.Component {
  constructor(props) {
    super(props);
    this.state ={
      showToast: false
    }
    this.handleSendCode = this.handleSendCode.bind(this);
    this.onDialogHandler = this.onDialogHandler.bind(this);
    this.timerHandler = this.timerHandler.bind(this);

    props.initBind();
  }

  onDialogHandler() {
    // 这块搞反了。。。md。在通过微信推送消息打开这个页面的时候，fromMsg是undefined，就这么筹和看吧
    if (!this.props.fromMsg) {
      window.WeixinJSBridge.call('closeWindow');
    } else {
      this.props.backHandler();
    }
  }

  timerHandler(first) {
    window.clearTimeout(this.props.state.timer);
    this.props.stateChange('sendCodeStr', this.props.state.time + 's');
    if((this.props.state.time===0 || this.props.state.isWaitting === false)&&!first){
      this.props.stateChange('sendCodeStr', '重新获取(120s)');
      this.props.stateChange('time', 120);
    } else {
      this.props.stateChange('time', this.props.state.time - 1);
      let timer = setTimeout(this.timerHandler, 1000);
      this.props.stateChange('timer', timer);
    }
  }

  handleSendCode() {
    this.props.stateChange('isWaitting', true);
    this.timerHandler(true);
  }

  componentWillUnmount() {
    this.props.stateChange('isWaitting', false);
    this.props.stateChange('time', 120);
    window.clearTimeout(this.props.state.timer);
  }

  componentDidMount() {
    document.title = '填写验证码';

    if (!this.props.fromMsg) {
      let {
        location = {}
      } = this.props;
  
      let query = parseQueryString(location.search || '?code=');
      this.props.getPersonalInfo(query.code);
    }
  }

  render() {
    let {
      sendCode,
      data,
      error
    } = this.props;
    let reg = /^((13|18|17)[0-9]|147|15[0-35-9])\d{8}$/;

    let canSendCode = reg.test(data.mobile)&&(this.props.state.time === 120);

    return (
      <div className='bind'>
        <div className="weui-cells weui-cells_form">
          <div className="weui-cell">
            <div className="weui-cell__hd"><label className="weui-label">手机号</label></div>
            <div className="weui-cell__bd">
              <input className="weui-input" type="number" placeholder="请输入手机号" 
                value={data.mobile}
                onChange={ (e) => {
                  let value = e.target.value
                  if (value.length <= 11) {
                    this.props.dataChange('mobile', e.target.value);
                  }
                }}
              />
            </div>
          </div>
          <div className="weui-cell weui-cell_vcode">
            <div className="weui-cell__hd">
              <label className="weui-label">验证码</label>
            </div>
            <div className="weui-cell__bd">
              <input className="weui-input" type="number" pattern="[0-9]*" placeholder="请输入验证码" 
                value={data.veCode}
                onChange={ (e) => {
                  let value = e.target.value
                  if (value.length <= 4) {
                    this.props.dataChange('veCode', e.target.value);
                  }
                }}
              />
            </div>
            <div className="weui-cell__ft">
              <button className={classnames('weui-vcode-btn', {'code-disabled': !canSendCode})}
                onClick={() => {
                  if (canSendCode) {
                    sendCode(data.mobile);
                    this.handleSendCode();
                  }
                }}
              >{this.props.state.sendCodeStr}</button>
            </div>
          </div>
        </div>
        <div className='btn-group'>
          <a href="javascript:;" className="weui-btn weui-btn_submit"
            onClick={()=>{
              if (data.mobile.length<11) {
                this.props.showError('请输入正确的手机号');
              } else if (data.veCode.length<4) {
                this.props.showError('请输入正确的验证码');
              } else {
                this.props.doEnsure({
                  ...data
                }, () => {
                  let {
                    match
                  } = this.props;
                  if (match.params.periodId) {
                    this.props.doSign(match.params.periodId, () => {
                      this.setState({
                        showToast: true
                      })
                    })
                  } else {
                    this.setState({
                      showToast: true
                    })
                  }
                })
              }
            }}
          >提交</a>
          <a href="javascript:;" className="weui-btn weui-btn_back"
            onClick={()=>{
              this.onDialogHandler();
            }}
          >返回</a>
        </div>
        <Toast iconSize="" icon="warn" show={error.hasError}>{error.msg}</Toast>
        <Toast iconSize="" icon="warn" show={this.props.personalInfo.error.hasError}>发生了网络错误</Toast>
        <Dialog 
          type="android" 
          title={'绑定成功！'} 
          buttons={[{
            type:'primary',
            label:'知道了',
            onClick: this.onDialogHandler
          }]}
          show={this.state.showToast}>
              恭喜您的手机号已绑定成功。
        </Dialog>
      </div>
    )
  }
}

export default connect( (store) => {
  return {
    ...store.bind,
    personalInfo: store.personalInfo
  }
}, {
  ...actions,
  getPersonalInfo
})(BindView);
